#include "linux_def.h"
#include "core.h"
#include "event.h"

rbtree_t	event_timer_rbtree;	//超时管理使用的红黑树
static rbtree_node_t	event_timer_sentinel;	//哨兵节点

int event_timer_init()
{
	// 创建一颗空红黑树
	rbtree_init(&event_timer_rbtree, &event_timer_sentinel, rbtree_insert_timer_value);

	//多线程的时候初始话锁
#if (THREADS)
	
#endif
}

int event_find_timer()
{
	int	timer;
	rbtree_node_t	*node, *root, *sentinel;

	if (event_timer_rbtree.root == &event_timer_sentinel)
		return -1;

	root = event_timer_rbtree.root;
	sentinel = event_timer_rbtree.sentinel;

	node = rbtree_min(root, sentinel);

	timer = (int)node->key - (int)current_msec;

	if (verbose)
		fprintf(stderr, "event_find_timer\n");

	return (uintptr_t)(timer>0?timer:0);
}

void event_expire_timers()
{
	event_t	*ev;
	rbtree_node_t	*node, *root, *sentinel;

	sentinel = event_timer_rbtree.sentinel;

	for (;;){
		root = event_timer_rbtree.root;

		if (root == sentinel)	
			return;

		node = rbtree_min(root, sentinel);

		if ((int)(node->key - current_msec) <= 0){
			ev = (event_t*)((char *)node - offsetof(event_t, timer));

			rbtree_delete(&event_timer_rbtree, &ev->timer);
			ev->timer_set = 0;
			ev->timedout = 1;
			ev->handler(ev);
			continue;
		}
		break;
	}
}
